package com.xjscrm.server.service.soptask.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.annotation.MerId;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.enums.RedisCacheKeyEnum;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.common.vo.grouppull.GroupPullData;
import com.xjscrm.common.vo.grouppull.GroupPullMsgData;
import com.xjscrm.common.vo.sop.HangerTigger;
import com.xjscrm.common.vo.sop.PlanData;
import com.xjscrm.server.biz.RatelimitService;
import com.xjscrm.server.common.util.DeviceTools;
import com.xjscrm.server.common.util.GroupTools;
import com.xjscrm.server.common.util.PlanDataTools;
import com.xjscrm.server.dto.soptask.SopTaskCustomerQuery;
import com.xjscrm.server.dto.wwcustomer.WwCustomerQuery;
import com.xjscrm.server.dto.wwgroup.WwGroupQuery;
import com.xjscrm.server.mapper.*;
import com.xjscrm.server.req.filterrule.CustomerBasicInfoExcludeFilterReq;
import com.xjscrm.server.req.filterrule.CustomerTimeExcludeFilterReq;
import com.xjscrm.server.req.filterrule.CustomerTagsExcludeFilterReq;
import com.xjscrm.server.service.customer.WwCustomerTagsService;
import com.xjscrm.server.service.filterrule.CustomerCommonFilterService;
import com.xjscrm.server.service.grouppull.GroupPullDataService;
import com.xjscrm.server.service.soptask.SopJobHanderService;
import com.xjscrm.server.service.soptask.SopJobMsgService;
import com.xjscrm.server.vo.device.Device;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;

/**
 * SOP任务
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class SopJobHanderServiceImpl implements SopJobHanderService, CustomerCommonFilterService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SopTaskMapper sopTaskMapper;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private WwCustomerMapper wwCustomerMapper;
    @Autowired
    private WwGroupTagsRelationMapper wwGroupTagsRelationMapper;
    @Autowired
    private WwCustomerBlacklistMapper wwCustomerBlacklistMapper;
    @Autowired
    private WwCustomerTagsMapper wwCustomerTagsMapper;
    @Autowired
    private SopTaskCustomerMapper sopTaskCustomerMapper;
    @Autowired
    private WwGroupMapper wwGroupMapper;
    @Autowired
    private SopJobMapper sopJobMapper;
    @Autowired
    private GroupPullDataService groupPullDataService;
    @Autowired
    private SopJobMsgService sopJobMsgService;
    @Autowired
    private WwDeviceMapper wwDeviceMapper;
    @Autowired
    private SopTemplateMapper sopTemplateMapper;
    @Autowired
    private SopTaskDeviceConfigMapper sopTaskDeviceConfigMapper;
    @Resource
    private WwCustomerTagsService wwCustomerTagsService;

    /**
     * 添加手动SOPjob
     *
     * @param merId
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForXxJob")
    @TraceGenerate //注入消息id标签
    public void addSopJobByHander(@MerId Long merId, SopTask sopTask, SopTaskDevice sopTaskDevice) {
        if (sopTask == null) {
            return;
        }

        if (sopTaskDevice == null) {
            return;
        }

        //类型(1-手动sop;2-新客户sop;3-标签sop;4-群sop)
        Integer type = Tools.getInteger(sopTask.getType());
        if (type.intValue() != 1) {
            return;
        }

        int now = DateUtil.getTime();

        //获取手动触发规则
        String trigger = sopTask.getTrigger();
        if (StringUtils.isBlank(trigger)) {
            return;
        }

        HangerTigger hangerTigger = JSONObject.parseObject(trigger, HangerTigger.class);
        if (hangerTigger == null) {
            return;
        }

        //是否开启会员发送消息
        Integer customerSwitch = Tools.getInteger(hangerTigger.getCustomerSwitch());
        if (customerSwitch.intValue() == 1) {//开启客户发送消息，则遍历客户表，依次发送消息
            //筛选类型(0-全部客户；1-筛选客户；2-选择客户)
            Integer customerType = Tools.getInteger(hangerTigger.getCustomerType());
            if (customerType.intValue() == 0 || customerType.intValue() == 1) {//需要遍历客户表
                //查询所有的客户
                WwCustomerQuery wwCustomerQuery = new WwCustomerQuery();
                wwCustomerQuery.setMerId(sopTask.getMerId());
                wwCustomerQuery.setDeviceUniqueId(sopTaskDevice.getDeviceUniqueId());
                Page<WwCustomer> page = new Page<>();
                page.setCurrent(1);//只查第一页
                page.setSize(10); //每页查询10个
                page.addOrder(OrderItem.asc("id"));//默认id升序
                Long idStart = 0L;
                List<WwCustomer> wwCustomerList = wwCustomerMapper.findByList(page, wwCustomerQuery);
                while (wwCustomerList != null && wwCustomerList.size() > 0) {
                    for (WwCustomer wwCustomer : wwCustomerList) {
                        try {
                            if (wwCustomer.getId().longValue() >idStart.longValue()) {
                                idStart = wwCustomer.getId();
                            }
                            //客户验证结果，默认为通过验证
                            boolean result = true;
                            if (customerType.intValue() == 1) { //按照条件筛选客户，需要验证
                                result = verifyCustomer(sopTask, hangerTigger, sopTaskDevice, wwCustomer, null, 0);
                            }
                            if (result) {//符合条件，则添加消息
                                addSopJob(sopTask, sopTaskDevice, wwCustomer, null, 0);
                            }
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }

                    wwCustomerQuery.setIdStart(idStart);
                    wwCustomerList = wwCustomerMapper.findByList(page, wwCustomerQuery);
                }
            } else if (customerType.intValue() == 2) { //选择客户
                //查询选择的客户
                SopTaskCustomerQuery sopTaskCustomerQuery = new SopTaskCustomerQuery();
                sopTaskCustomerQuery.setMerId(sopTask.getMerId());
                sopTaskCustomerQuery.setDeviceUniqueId(sopTaskDevice.getDeviceUniqueId());
                sopTaskCustomerQuery.setType(0); //类型（0-私聊;1-群聊）
                sopTaskCustomerQuery.setTaskId(sopTask.getId());
                Page<SopTaskCustomer> page = new Page<>();
                page.setCurrent(1);//只查第一页
                page.setSize(10); //每页查询10个
                page.addOrder(OrderItem.asc("id"));//默认id升序
                Long idStart = 0L;
                List<SopTaskCustomer> sopTaskCustomerList = sopTaskCustomerMapper.findByList(page, sopTaskCustomerQuery);
                while (sopTaskCustomerList != null && sopTaskCustomerList.size() > 0) {
                    for (SopTaskCustomer sopTaskCustomer : sopTaskCustomerList) {
                        try {
                            if (sopTaskCustomer.getId().longValue() >idStart.longValue()) {
                                idStart = sopTaskCustomer.getId();
                            }

                            //默认黑名单不通过
                            WwCustomerBlacklist wwCustomerBlacklist = wwCustomerBlacklistMapper.selectByWxid(sopTaskCustomer.getMerId(), sopTaskCustomer.getWxid());
                            if (wwCustomerBlacklist != null) { //在黑名单中
                                log.info("黑名单会员wxid={}, merId={}", sopTaskCustomer.getWxid(), sopTaskCustomer.getMerId());
                                continue;
                            }

                            WwCustomer wwCustomer = wwCustomerMapper.queryByDeviceUniqueIdAndWxid(sopTaskCustomer.getDeviceUniqueId(), sopTaskCustomer.getWxid());
                            if (wwCustomer != null) {
                                addSopJob(sopTask, sopTaskDevice, wwCustomer, null, 0);
                            }
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                    sopTaskCustomerQuery.setIdStart(idStart);
                    sopTaskCustomerList = sopTaskCustomerMapper.findByList(page, sopTaskCustomerQuery);
                }
            }
        }

        //是否开启群发送消息
        Integer groupSwitch = Tools.getInteger(hangerTigger.getGroupSwitch());
        if (groupSwitch.intValue() == 1) {//开启群发送消息，则遍历群表，依次发送消息

            //筛选类型(0-全部群；1-筛选群；2-选择群)
            Integer groupType = Tools.getInteger(hangerTigger.getGroupType());
            if (groupType.intValue() == 0 || groupType.intValue() == 1) {//需要遍历群表
                //查询所有的客户
                WwGroupQuery wwGroupQuery = new WwGroupQuery();
                wwGroupQuery.setMerId(sopTask.getMerId());
                wwGroupQuery.setDeviceUniqueId(sopTaskDevice.getDeviceUniqueId());
                Page<WwGroup> page = new Page<>();
                page.setCurrent(1);//只查第一页
                page.setSize(10); //每页查询10个
                page.addOrder(OrderItem.asc("id"));//默认id升序
                Long idStart = 0L;
                List<WwGroup> wwGroupList = wwGroupMapper.findByList(page, wwGroupQuery);
                while (wwGroupList != null && wwGroupList.size() > 0) {
                    for (WwGroup wwGroup : wwGroupList) {
                        try {
                            if (wwGroup.getId().longValue() >idStart.longValue()) {
                                idStart = wwGroup.getId();
                            }
                            //客户验证结果，默认为通过验证
                            boolean result = true;
                            if (groupType.intValue() == 1) { //按照条件筛选客户，需要验证
                                result = verifyCustomer(sopTask, hangerTigger, sopTaskDevice, null, wwGroup, 1);
                            }

                            if (result) {//符合条件，则添加消息
                                addSopJob(sopTask, sopTaskDevice, null, wwGroup, 1);
                            }
                        } catch (Exception e) {
                            log.error("--循环所有客户群发消息失败--error={}", e.getMessage(), e);
                        }
                    }

                    wwGroupQuery.setIdStart(idStart);
                    wwGroupList = wwGroupMapper.findByList(page, wwGroupQuery);
                }
            } else if (groupType.intValue() == 2) { //遍历选择的群列表
                //查询选择的客户
                SopTaskCustomerQuery sopTaskCustomerQuery = new SopTaskCustomerQuery();
                sopTaskCustomerQuery.setMerId(sopTask.getMerId());
                sopTaskCustomerQuery.setDeviceUniqueId(sopTaskDevice.getDeviceUniqueId());
                sopTaskCustomerQuery.setType(1); //类型（0-私聊;1-群聊）
                sopTaskCustomerQuery.setTaskId(sopTask.getId());

                Page<SopTaskCustomer> page = new Page<>();
                page.setCurrent(1);//只查第一页
                page.setSize(10); //每页查询10个
                page.addOrder(OrderItem.asc("id"));//默认id升序
                Long idStart = 0L;
                List<SopTaskCustomer> sopTaskCustomerList = sopTaskCustomerMapper.findByList(page, sopTaskCustomerQuery);
                while (sopTaskCustomerList != null && sopTaskCustomerList.size() > 0) {
                    for (SopTaskCustomer sopTaskCustomer : sopTaskCustomerList) {
                        try {
                            if (sopTaskCustomer.getId().longValue() >idStart.longValue()) {
                                idStart = sopTaskCustomer.getId();
                            }

                            WwGroup wwGroup = wwGroupMapper.queryByDeviceUniqueIdAndGroupWxid(sopTaskCustomer.getDeviceUniqueId(), sopTaskCustomer.getWxid());
                            if (wwGroup != null) {
                                addSopJob(sopTask, sopTaskDevice, null, wwGroup, 1);
                            }
                        } catch (Exception e) {
                            log.error("--循环选择的客户群发消息失败--error={}", e.getMessage(), e);
                        }
                    }

                    sopTaskCustomerQuery.setIdStart(idStart);
                    sopTaskCustomerList = sopTaskCustomerMapper.findByList(page, sopTaskCustomerQuery);
                }
            }
        }
    }

    /**
     * 验证会员是否符合条件
     *
     * @param wwCustomer 聊天消息
     * @param type       0-客户；1-群
     * @return 实例对象
     */
    private boolean verifyCustomer(SopTask sopTask, HangerTigger hangerTigger, SopTaskDevice sopTaskDevice, WwCustomer wwCustomer, WwGroup wwGroup, int type) {

        //是否开启群聊开关
        if (type == 1) {//群

            if (wwGroup == null) {
                return false;
            }

            //群wxid
            String groupWxId = Tools.getStr(wwGroup.getGroupWxid());
            String groupName = Tools.getStr(wwGroup.getGroupName());

            //查找此机器人是否在群内成员
//            WwGroupMember wwGroupMember = wwGroupMemberMapper.selectByGroupWxidAndWxid(wwGroup.getMerId(), wwGroup.getGroupWxid(), wwGroup.getDeviceId());
//            if(wwGroupMember == null){
//                return false;
//            }

            //群类型(0-全部客户；1-部分客户)
            Integer groupType = Tools.getInteger(hangerTigger.getGroupType());
            if (groupType.intValue() == 1) { //部分客户，则需要验证条件

                //群名关键词选项(0-含任意关键词；1-含所有关键词)
                Integer groupNameKeywordOpt = hangerTigger.getGroupNameKeywordOpt();
                if (groupNameKeywordOpt != null) {
                    //群名关键词列表
                    List<String> groupNameKeywordList = JSONObject.parseArray(hangerTigger.getGroupNameKeywords(), String.class);
                    if (groupNameKeywordList == null || groupNameKeywordList.size() == 0) { //没有找到，则不回复
                        return false;
                    }

                    if (groupNameKeywordOpt.intValue() == 0) { //满足任意一个
                        boolean groupNameKeywordFlag = false;
                        for (String keyword : groupNameKeywordList) {
                            if (groupName.contains(keyword)) {//找到一个符合的，就返回通过
                                groupNameKeywordFlag = true;
                            }
                        }
                        if (!groupNameKeywordFlag) {
                            return false;
                        }
                    } else {//满足所有触发
                        for (String keyword : groupNameKeywordList) {
                            if (!groupName.contains(keyword)) {//找到一个不符合的，就返回不通过
                                return false;
                            }
                        }
                    }
                }

                //群标签选项(0-含任意标签；1-含所有标签；2-未打任何标签)
                Integer groupTagOpt = hangerTigger.getGroupTagOpt();
                if (groupTagOpt != null) {

                    //封装此群已打的标签
                    List<WwGroupTagsRelation> wwGroupTagsRelationList = wwGroupTagsRelationMapper.selectByDeviceIdAndGroupWxid(sopTaskDevice.getMerId(), sopTaskDevice.getDeviceId(), groupWxId);
                    List<Long> wwGroupTagedList = new ArrayList<>();
                    if (wwGroupTagsRelationList != null && wwGroupTagsRelationList.size() > 0) {
                        for (WwGroupTagsRelation wwGroupTagsRelation : wwGroupTagsRelationList) {
                            wwGroupTagedList.add(wwGroupTagsRelation.getTagId());
                        }
                    }

                    //2-未打任何标签
                    if (groupTagOpt.intValue() == 2) {
                        if (wwGroupTagedList.size() > 0) {
                            return false;
                        }
                    } else {
                        //标签列表
                        List<Long> groupTagList = JSONObject.parseArray(hangerTigger.getGroupTags(), Long.class);
                        if (groupTagList == null || groupTagList.size() == 0) { //没有找到，则不回复
                            return false;
                        }
                        if (groupTagOpt.intValue() == 0) { //满足任意一个
                            boolean tagFlag = false;
                            for (Long groupTag : groupTagList) {
                                if (wwGroupTagedList.contains(groupTag)) {//找到一个符合的，就返回通过
                                    tagFlag = true;
                                    break;
                                }
                            }
                            if (!tagFlag) {
                                return false;
                            }
                        } else if (groupTagOpt.intValue() == 1) {//满足所有触发
                            if (!wwGroupTagedList.containsAll(groupTagList)) {
                                return false;
                            }
                        }
                    }
                }

                //群成员角色列表(0-群主；1-管理员；2-普通成员)
                String groupMemberIdentitys = hangerTigger.getGroupMemberIdentitys();
                List<Integer> groupMemberIdentityList = JSONObject.parseArray(groupMemberIdentitys, Integer.class);
                if (groupMemberIdentityList != null && groupMemberIdentityList.size() > 0) {
                    boolean identityFlag = GroupTools.verifyIdentity(wwGroup, groupMemberIdentityList, sopTaskDevice.getDeviceId());
                    if (!identityFlag) {
                        return false;
                    }
                }

                //验证群人数
                Integer groupMemberTotalMin = hangerTigger.getGroupMemberTotalMin();
                Integer groupMemberTotalMax = hangerTigger.getGroupMemberTotalMax();
                if (groupMemberTotalMin != null
                        && groupMemberTotalMax != null
                        && groupMemberTotalMin.intValue() <= groupMemberTotalMin.intValue()
                ) {
                    //在群人数
                    String groupMemberCountKey = String.format(RedisCacheKeyEnum.GROUP_MEMBER_COUNT.getKey(), groupWxId);
                    Integer groupMemberCount = (Integer) redisTemplate.opsForValue().get(groupMemberCountKey);
                    Integer memberTotal = Tools.getInteger(groupMemberCount);
                    if (memberTotal.intValue() < groupMemberTotalMin.intValue()
                            || memberTotal.intValue() > groupMemberTotalMax.intValue()
                    ) {
                        return false;
                    }
                }

                //验证建群时间
                String groupCreateDayStart = hangerTigger.getGroupCreateDayStart();
                String groupCreateDayEnd = hangerTigger.getGroupCreateDayEnd();
                if (StringUtils.isNotBlank(groupCreateDayStart)
                        && StringUtils.isNotBlank(groupCreateDayEnd)
                ) {
                    Integer groupCreateTime = wwGroup.getGroupCreateTime();
                    if (groupCreateTime == null) {//如果没有建群时间，则不通过
                        return false;
                    }
                    //判断旧发送时间是否在允许区间内
                    Instant instant_groupCreateTime = Instant.ofEpochMilli(groupCreateTime * 1000L);
                    LocalDateTime localDateTime = LocalDateTime.ofInstant(instant_groupCreateTime, ZoneId.systemDefault());
                    boolean withinTimeInterval_groupCreateTime = Tools.isWithinDateInterval(localDateTime, LocalDate.parse(groupCreateDayStart), LocalDate.parse(groupCreateDayEnd));
                    if (!withinTimeInterval_groupCreateTime) {
                        return false;
                    }
                }
            }
        } else {//会员
            if (wwCustomer == null) {
                return false;
            }

            //是否开启群聊开关
            Integer customerSwitch = Tools.getInteger(hangerTigger.getCustomerSwitch());
            if (customerSwitch.intValue() == 0) { //不开启客户消息，直接不通过
                return false;
            }

            //默认黑名单不通过
            WwCustomerBlacklist wwCustomerBlacklist = wwCustomerBlacklistMapper.selectByWxid(sopTask.getMerId(), wwCustomer.getWxid());
            if (wwCustomerBlacklist != null) { //在黑名单中
                log.info("黑名单会员wxid={}, merId={}", wwCustomer.getWxid(), wwCustomer.getMerId());
                return false;
            }

            //客户类型(0-全部客户；1-部分客户)
            Integer customerType = Tools.getInteger(hangerTigger.getCustomerType());
            if (customerType.intValue() == 1) { //部分客户，则需要验证条件
                //获取客户已打的标签
                List<Long> wwCustomerTagedList = wwCustomerTagsService.getTagIds(wwCustomer.getMerId(), wwCustomer.getId());
                //排除用户
                CustomerTagsExcludeFilterReq customerTagsExcludeFilterReq = new CustomerTagsExcludeFilterReq(hangerTigger.getExcludeCustomerEnterpriseTagOpt(), hangerTigger.getExcludeCustomerEnterpriseTags(), wwCustomerTagedList, hangerTigger.getOpenExclude());
                CustomerTimeExcludeFilterReq customerTimeExcludeFilterReq = new CustomerTimeExcludeFilterReq(hangerTigger.getExcludeNewCustomer(), wwCustomer.getCreateTime(), hangerTigger.getExcludeCustomerCreateDayStart(), hangerTigger.getExcludeCustomerCreateDayEnd(), hangerTigger.getOpenExclude());
                CustomerBasicInfoExcludeFilterReq customerBasicInfoExcludeFilterReq = new CustomerBasicInfoExcludeFilterReq(wwCustomer, hangerTigger.getExcludeCustomerRemarkOpt(), hangerTigger.getExcludeCustomerGenders(), hangerTigger.getOpenExclude());
                if (this.excludeFilter(customerTagsExcludeFilterReq, customerTimeExcludeFilterReq, customerBasicInfoExcludeFilterReq)) {
                    return false;
                }
                //客户企业标签选项(0-含任意标签；1-含所有标签；2-未打任何标签)
                Integer customerEnterpriseTagOpt = hangerTigger.getCustomerEnterpriseTagOpt();
                if (customerEnterpriseTagOpt != null) {
                    //2-未打任何标签
                    if (customerEnterpriseTagOpt.intValue() == 2) {
                        if (wwCustomerTagedList.size() > 0) {
                            return false;
                        }
                    } else {
                        //标签列表
                        List<Long> customerEnterpriseTagList = JSONObject.parseArray(hangerTigger.getCustomerEnterpriseTags(), Long.class);
                        if (customerEnterpriseTagList == null || customerEnterpriseTagList.size() == 0) { //没有找到，则不回复
                            return false;
                        }
                        if (customerEnterpriseTagOpt.intValue() == 0) { //满足任意一个
                            boolean tagFlag = false;
                            for (Long customerEnterpriseTag : customerEnterpriseTagList) {
                                if (wwCustomerTagedList.contains(customerEnterpriseTag)) {//找到一个符合的，就返回通过
                                    tagFlag = true;
                                    break;
                                }
                            }
                            if (!tagFlag) {
                                return false;
                            }
                        } else if (customerEnterpriseTagOpt.intValue() == 1) {//满足所有触发
                            if (!wwCustomerTagedList.containsAll(customerEnterpriseTagList)) {
                                return false;
                            }
                        }
                    }
                }

                //加好友时间
                String customerCreateDayStart = hangerTigger.getCustomerCreateDayStart();
                String customerCreateDayEnd = hangerTigger.getCustomerCreateDayEnd();
                if (StringUtils.isNotBlank(customerCreateDayStart)
                        && StringUtils.isNotBlank(customerCreateDayEnd)
                ) {
                    Integer customerCreateTime = wwCustomer.getCreateTime();
                    if (customerCreateTime == null) {//如果没有添加好友时间，则不通过
                        return false;
                    }
                    //判断旧发送时间是否在允许区间内
                    Instant instant_groupCreateTime = Instant.ofEpochMilli(customerCreateTime * 1000L);
                    LocalDateTime localDateTime = LocalDateTime.ofInstant(instant_groupCreateTime, ZoneId.systemDefault());
                    boolean withinTimeInterval_customerCreateTime = Tools.isWithinDateInterval(localDateTime, LocalDate.parse(customerCreateDayStart), LocalDate.parse(customerCreateDayEnd));
                    if (!withinTimeInterval_customerCreateTime) {
                        return false;
                    }
                }

                //客户备注选项(0-无备注；1-有备注)
                Integer customerRemarkOpt = hangerTigger.getCustomerRemarkOpt();
                if (customerRemarkOpt != null) {
                    if (customerRemarkOpt.intValue() == 0) {//无备注
                        if (StringUtils.isNotBlank(wwCustomer.getRemark())) {
                            return false;
                        }
                    } else if (customerRemarkOpt.intValue() == 1) { //有备注
                        if (StringUtils.isBlank(wwCustomer.getRemark())) {
                            return false;
                        }
                    }
                }

                //性别(0-未知；1-男；2-女)
                Integer customerGenders = hangerTigger.getCustomerGenders();
                if (customerGenders != null) {
                    //验证客户性别是否跟配置的符合
                    if (customerGenders.intValue() != Tools.getInteger(wwCustomer.getGender()).intValue()) {
                        return false;
                    }
                }
            }
        }
        return true;
    }


    /**
     * 封装消息
     *
     * @param sopTask
     * @param sopTaskDevice
     * @param wwCustomer
     * @param wwGroup
     * @param type          类型（0-私聊;1-群聊）
     * @return int
     * @author jitwxs
     * @date 2024/4/1 18:52
     */
    public void addSopJob(SopTask sopTask, SopTaskDevice sopTaskDevice, WwCustomer wwCustomer, WwGroup wwGroup, int type) {

        if(sopTask.getTeaplateId() == null){
            return;
        }

        SopTemplate sopTemplate = sopTemplateMapper.selectById(sopTask.getTeaplateId());
        if(sopTemplate == null){
            return;
        }

        String planDatas = sopTemplate.getPlanDatas();
        if (StringUtils.isBlank(planDatas)) {
            return;
        }

        List<PlanData> planDataList = JSONObject.parseArray(planDatas, PlanData.class);
        if (planDataList == null || planDataList.size() == 0) {
            return;
        }

        String sendWxid = null;
        if (type == 1) {//群聊
            if (wwGroup != null) {
                sendWxid = wwGroup.getGroupWxid();
            }
        } else {//私聊
            if (wwCustomer != null) {
                sendWxid = wwCustomer.getWxid();
            }
        }

        if (StringUtils.isBlank(sendWxid)) {
            return;
        }
        int now = DateUtil.getTime();

        //计算发送时间
        Integer sendTime = PlanDataTools.getSendTime(null, planDataList.get(0));

        //保存SOPJOB
        SopJob sopJob = new SopJob();
        sopJob.setId(IdWorker.getId());
        sopJob.setMerId(sopTask.getMerId());
        sopJob.setTaskId(sopTask.getId());
        sopJob.setName(sopTask.getName());
        sopJob.setStatus(1);
        sopJob.setType(sopTask.getType());
        sopJob.setTeaplateId(sopTask.getTeaplateId());
        sopJob.setTrigger(sopTask.getTrigger());
        sopJob.setPlanDatas(sopTemplate.getPlanDatas());
        sopJob.setWxid(sendWxid);
        sopJob.setDeviceUniqueId(sopTaskDevice.getDeviceUniqueId());
        sopJob.setDeviceId(sopTaskDevice.getDeviceId());
        sopJob.setFirstTime(sendTime);
        sopJob.setNextTime(sendTime);
        sopJob.setPlanDatasNextIndex(0);
        sopJob.setWxidType(type);//类型（0-客户;1-群）
        sopJob.setCreateTime(now);
        sopJob.setUpdateTime(now);
        sopJobMapper.insertSelective(sopJob);
    }


    /**
     * 自动处理手动SOP阶段性任务
     *
     * @param sopJob
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForXxJob")
    @TraceGenerate //注入消息id标签
    public void autoStepSopJobByHander(SopJob sopJob){

        if(sopJob == null){
            return;
        }

        //获取该任务计划数据
        String planDatas = sopJob.getPlanDatas();
        if (StringUtils.isBlank(planDatas)) {
            return;
        }

        List<PlanData> planDataList = JSONObject.parseArray(planDatas, PlanData.class);
        if (planDataList == null || planDataList.size() == 0) {
            return;
        }

        int now = DateUtil.getTime();

        //获取当前阶段性数据的下标
        Integer planDatasNextIndex = Tools.getInteger(sopJob.getPlanDatasNextIndex());
        //如果下标已经超过数据的长度，则将任务修改成已完成
        if(planDatasNextIndex >= planDataList.size()){
            sopJob.setStatus(2); //执行完成
            sopJob.setUpdateTime(now);
            sopJobMapper.updateStatusById(sopJob);
            return;
        }

        //查询机器人
        WwDevice wwDevice = wwDeviceMapper.queryById(sopJob.getDeviceUniqueId());
        if(wwDevice == null){
            sopJob.setStatus(0); //执行关闭
            sopJob.setUpdateTime(now);
            sopJob.setRemark("机器人未找到");
            sopJobMapper.updateStatusById(sopJob);
            return;
        }
        Device device = DeviceTools.transDevice(wwDevice);

        //查询会员
        WwCustomer wwCustomer = null;
        String sendNickname = null;
        if(Tools.getInteger(sopJob.getWxidType()).intValue() == 0){
            wwCustomer = wwCustomerMapper.queryByDeviceUniqueIdAndWxid(sopJob.getDeviceUniqueId(), sopJob.getWxid());
            if(wwCustomer == null){ //客户不存在，咋关闭
                sopJob.setStatus(0); //执行关闭
                sopJob.setUpdateTime(now);
                sopJob.setRemark("会员未找到");
                sopJobMapper.updateStatusById(sopJob);
                return;
            }

            //默认黑名单不通过
            WwCustomerBlacklist wwCustomerBlacklist = wwCustomerBlacklistMapper.selectByWxid(sopJob.getMerId(), wwCustomer.getWxid());
            if(wwCustomerBlacklist != null){ //在黑名单中
                sopJob.setStatus(0); //执行关闭
                sopJob.setUpdateTime(now);
                sopJob.setRemark("黑名单会员");
                sopJobMapper.updateStatusById(sopJob);
                return;
            }

            //替换[称呼/昵称]变量，优先称呼，在昵称
            sendNickname = wwCustomer.getNickname();
            if(StringUtils.isBlank(sendNickname)){
                sendNickname = wwCustomer.getName();
            }

        }else{//群发
            WwGroup wwGroup = wwGroupMapper.queryByDeviceUniqueIdAndGroupWxid(sopJob.getDeviceUniqueId(), sopJob.getWxid());
            if(wwGroup == null){ //群不存在
                sopJob.setStatus(0); //执行关闭
                sopJob.setUpdateTime(now);
                sopJob.setRemark("群未找到");
                sopJobMapper.updateStatusById(sopJob);
                return;
            }
        }

        //本次的执行时间
        Integer sendTime_this = Tools.getInteger(sopJob.getNextTime());
        //获取当前需要发送的阶段性计划数据
        if(planDatasNextIndex < planDataList.size()){
            PlanData planData = planDataList.get(planDatasNextIndex);
            if(planData != null){
                List<GroupPullData> groupPullDataList = planData.getMsgDataList();
                if(groupPullDataList != null){
                    List<GroupPullMsgData> groupPullMsgDataList = groupPullDataService.handGroupPullData(sopJob.getMerId(), groupPullDataList, wwCustomer, device);
                    if (groupPullMsgDataList != null && groupPullMsgDataList.size() > 0) {
                        sopJobMsgService.addSopJobMsg(sopJob, sendTime_this, device, sopJob.getWxid(), sendNickname, groupPullMsgDataList);
                    }
                }
            }
        }

        if(planDatasNextIndex + 1 >= planDataList.size()){
            sopJob.setStatus(2);
            sopJob.setUpdateTime(now);
            sopJobMapper.updateStatusById(sopJob);
        }else{
            Integer sendTime_next = PlanDataTools.getSendTime(sopJob.getFirstTime(), planDataList.get(planDatasNextIndex + 1));
            sopJob.setNextTime(sendTime_next);
            sopJob.setPlanDatasNextIndex(planDatasNextIndex + 1);
            sopJob.setUpdateTime(now);
            sopJobMapper.updateStatusById(sopJob);
        }

    }

}
